import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Menu } from "antd";
import React, { useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
type MenuItem = Required<MenuProps>["items"][number];
// 登录请求到数据之后，就可以跟items匹配
const items: MenuItem[] = [
  {
    label: "栏目1",
    key: "/page1",
    icon: <PieChartOutlined />,
  },
  {
    label: "栏目2",
    key: "/page2",
    icon: <DesktopOutlined />,
  },
  {
    label: "栏目3",
    key: "/page3",
    icon: <UserOutlined />,
    children: [
      {
        label: "栏目301",
        key: "/page3/page301",
      },
      {
        label: "栏目302",
        key: "/page3/page302",
      },
      {
        label: "栏目303",
        key: "/page3/page303",
      },
    ],
  },
  {
    label: "栏目4",
    key: "/page4",
    icon: <TeamOutlined />,
    children: [
      {
        label: "栏目401",
        key: "/page4/page401",
      },
      {
        label: "栏目402",
        key: "/page4/page402",
      },
    ],
  },
  {
    label: "栏目5",
    key: "/page5",
    icon: <FileOutlined />,
  },
];

const MainMenu: React.FC = () => {
  const navigateTo = useNavigate();
  const currentRouter = useLocation();
  const menuClick = (e: { key: string }) => {
    // 点击跳转到对应路由  编程序导航 利用到一个hook
    navigateTo(e.key);
  };

  // 拿着currentRouter.pathname的值与items的key值进行对比，如果
  // 相等就获取上一级的key
  // 这个key 给到openKeys数组的元素，作为初始值

  let firstOpenKey: string = "";
  // 进行key 对比 find
  function findKey(obj:{key:string}) {
    return obj.key === currentRouter.pathname;
  }
  // 要对比多个children 循环
  for (let i = 0; i < items.length; i++) {
    // 判断是否能找到
    if (
      items[i]!["children"] &&
      items[i]!["children"].length > 1 &&
      items[i]!["children"].find(findKey)
    ) {
      firstOpenKey = items[i]!.key as string;
      break;
    }
  }
  // items[]["children"].find("") // 找到对应key，结果转为布尔值true

  // 设置展开项的初始值
  const [openKeys, setOpenKeys] = useState([firstOpenKey]);
  const handleOpenChange = (keys: string[]) => {
    // 展开和关闭的时候执行这里的代码
    // 把数组修改为点击的那一项
    setOpenKeys([keys[keys.length - 1]]);
  };

  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={[currentRouter.pathname]}
      mode="inline"
      // 菜单项数据
      items={items}
      onClick={menuClick}
      onOpenChange={handleOpenChange}
      // 当前菜单展开项key数组
      openKeys={openKeys}
    />
  );
};

export default MainMenu;
